package com.nidu.demo.tenant.executor.query;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.cola.dto.PageResponse;
import com.nidu.demo.tenant.convertor.TenantConvertor;
import com.nidu.demo.tenant.convertor.TenantCriteriaConvertor;
import com.nidu.demo.tenant.dto.TenantCO;
import com.nidu.demo.tenant.dto.TenantPageQry;
import com.nidu.demo.tenant.gateway.TenantGateway;
import com.nidu.demo.tenant.gateway.TenantPackageGateway;
import com.nidu.demo.tenant.model.Tenant;
import com.nidu.demo.tenant.model.TenantCriteria;
import com.nidu.demo.tenant.model.TenantPackage;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 租户分页查询执行器
 *
 * @author auto
 */
@Component
@RequiredArgsConstructor
public class TenantPageQryExe {

    private final TenantGateway gateway;

    private final TenantPackageGateway packageGateway;

    private final TenantConvertor convertor;

    private final TenantCriteriaConvertor criteriaConvertor;

    public PageResponse<TenantCO> execute(TenantPageQry qry) {
        TenantCriteria criteria = criteriaConvertor.toDataObject(qry);
        PageResponse<Tenant> page = gateway.pageByCondition(criteria);
        List<TenantCO> tenantCOS = convertor.toClientObjects(page.getData());
        Set<Long> packageIds = tenantCOS.stream().map(TenantCO::getPackageId).collect(Collectors.toSet());
        if(!CollUtil.isEmpty(packageIds)){
            List<TenantPackage> packageList = packageGateway.getByIds(packageIds);
            Map<Long, TenantPackage> packageMap = packageList.stream().collect(Collectors.toMap(TenantPackage::getId, Function.identity()));
            tenantCOS.forEach(item -> item.setPackageName(packageMap.get(item.getPackageId()).getName()));
        }
        return PageResponse.of(tenantCOS, page.getTotalCount(), page.getPageSize(), page.getPageIndex());
    }
}